package earogya.pharmacy.pharmacy;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import earogya.util.PharmacyHibernateUtil;
import earogya.pharmacy.pharmacy.OrderDrugs;
import earogya.pharmacy.pharmacy.ReleaseDrugs;

/*Class PharmacyHibernateManager
 * 
 * 
 * Save an object to database using hibernate
 * and dose other basic database functions
 * 
 * 
 * */
public class PharmacyHibernateManager {
	 
	public PharmacyHibernateManager() {
	}

	public int saveObject(Object obj) throws HibernateException {
		Integer id = 0;
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			id = (Integer) session.save(obj);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			throw e;
		}
		return id;
	}

	/**
	 * Query results from database based on the fields and values
	 * 
	 * @param fieldsAndValues
	 *            - names of the columns and their respective values
	 * @param required_field
	 *            - name of the required column
	 * @param table
	 *            - name of the table
	 * @return
	 */
	public int queryValuesFromDatabase(Object[][] fieldsAndValues,
			String required_field, String table) {
		int value = -1;
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();

		session.beginTransaction();
		SQLQuery query = session.createSQLQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, table));
		query.setMaxResults(1);
		List list = query.list();
		if (list.size() == 1) {
			value = (Integer) list.get(0);
		}
		return value;
	}

	public List queryAllFieldsFromDatabase(Object[][] fieldsAndValues,
			String table) {
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		session.beginTransaction();
		Query query = session.createQuery(this.buildSelectAllQuery(
				fieldsAndValues, table));
		list = query.list();

		return list;
	}

	public List queryValueListFromDatabase(Object[][] fieldsAndValues,
			String required_field, String table) {
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		session.beginTransaction();
		SQLQuery query = session.createSQLQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, table));
		list = query.list();

		return list;
	}

	public List queryValueListFromDatabase(Object[][] fieldsAndValues,
			String[] required_field, String className, String objectName) {
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		// try{
		session.beginTransaction();
		Query query = session.createQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, className, objectName));
		list = query.list();
		return list;
	}

	/**
	 * Creates an sql query using the given information.
	 * 
	 * @param fieldsAndValues
	 *            - name of the columns and their respective values
	 * @param required_field
	 *            - name of the required column
	 * @param table
	 *            - name of the table
	 * @return
	 */
	private String buildSelectQuery(Object[][] fieldsAndValues,
			String[] required_field, String className, String objectName) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT ");
		for (int i = 0; i < required_field.length; i++) {
			if (i < required_field.length - 1) {
				builder.append(objectName + "." + required_field[i] + ", ");
			} else {
				builder.append(objectName + "." + required_field[i] + " FROM "
						+ className + " AS " + objectName + " WHERE ");
			}
		}
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(objectName + "." + fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(objectName + "." + fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	/**
	 * Creates an sql query using the given information.
	 * 
	 * @param fieldsAndValues
	 *            - name of the columns and their respective values
	 * @param required_field
	 *            - names of the required column
	 * @param table
	 *            - name of the table
	 * @return
	 */
	private String buildSelectQuery(Object[][] fieldsAndValues,
			String required_field, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT " + required_field + " FROM " + table
				+ " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	private String buildSelectAllQuery(Object[][] fieldsAndValues, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT {patient.*} FROM " + table + " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	private String buildDeleteQuery(Object[][] fieldsAndValues, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("DELETE FROM " + table + " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	public Boolean deleteEntry(Object[][] fieldsAndValues, String table) {
		Boolean isSuccesful = false;
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			SQLQuery query = session.createSQLQuery(this.buildDeleteQuery(
					fieldsAndValues, table));
			int no_of_rows = query.executeUpdate();
			if (no_of_rows > 0) {
				isSuccesful = true;
			}
		} catch (HibernateException e) {
			isSuccesful = false;
		} 
		return isSuccesful;
	}

	public Boolean updateOrderDrugs(OrderDrugs order) {
		Boolean isSuccessful;
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			OrderDrugs order1 = (OrderDrugs) session.get(OrderDrugs.class,
					order.getOrderId());
			if (order.getDrugId() == 0) {
			} else {
				order1.setDrugId(order.getDrugId());
			}
			if (order.getQuantity() == 0) {
			} else {
				order1.setQuantity(order.getQuantity());
			}
			if (order.getOrderDate() == null) {
			} else {
				order1.setOrderDate(order.getOrderDate());
			}
			if (order.getOrderTime() == null) {
			} else {
				order1.setOrderTime(order.getOrderTime());
			}
			session.update(order1);
			session.getTransaction().commit();
			isSuccessful = true;
		} catch (HibernateException e) {
			isSuccessful = false;
			throw e;
		}
		return isSuccessful;
	}
	
	public Boolean updateReleaseDrugs(ReleaseDrugs release) {
		Boolean isSuccessful;
		Session session = PharmacyHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			ReleaseDrugs release1 = (ReleaseDrugs) session.get(ReleaseDrugs.class,
					release.getReleaseId());
			if (release.getPatientId() == 0) {
			} else {
				release1.setPatientId(release.getPatientId());
			}
			if (release.getDrugId() == 0) {
			} else {
				release1.setDrugId(release.getDrugId());
			}
			if (release.getQuantity() == 0) {
			} else {
				release1.setQuantity(release.getQuantity());
			}
			if (release.getUnits() == null) {
			} else {
				release1.setUnits(release.getUnits());
			}
			if (release.getUnitOrWard() == null) {
			} else {
				release1.setUnitOrWard(release.getUnitOrWard());
			}
			if (release.getReleaseDate() == null) {
			} else {
				release1.setReleaseDate(release.getReleaseDate());
			}
			if (release.getReleaseTime() == null) {
			} else {
				release1.setReleaseTime(release.getReleaseTime());
			}
			session.update(release1);
			session.getTransaction().commit();
			isSuccessful = true;
		} catch (HibernateException e) {
			isSuccessful = false;
			throw e;
		}
		return isSuccessful;
	}
}
